package ncs.modelo.impl;

import java.util.ArrayList;
import java.util.List;
import ncs.modelo.dao.CompradorDao;
import ncs.modelo.entidades.TCliente;
import ncs.modelo.util.HibernateUtil;
import org.hibernate.Query;
import org.hibernate.Session;

/**
 *
 * @author yoel
 */
public class CompradorDaoImpl implements CompradorDao {

    @Override
    public void insertar(TCliente comprador) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        try {
            session.beginTransaction();
            String nuevoID = getIDComprador();
            comprador.setCdCliente(nuevoID);
            comprador.setEstado(true);
            session.save(comprador);
            session.beginTransaction().commit();
        } catch (Exception e) {
            System.out.println("Error en insertar: " + e.getMessage());
            session.beginTransaction().rollback();
        }
    }

    private String getIDComprador() {
        Session session = HibernateUtil.getSessionFactory().openSession();
        String nuevoID = "";
        try {
            Query qry = session.createSQLQuery("SELECT idCliente();");
            ArrayList<String> idNuevo = (ArrayList<String>) qry.list();
            nuevoID = idNuevo.size() > 0 ? idNuevo.get(0) : "";
        } catch (Exception e) {
            System.out.println("\nError en getIDComprador: " + e.getMessage());
        }
        return nuevoID;
    }

    @Override
    public void actualizar(TCliente comprador) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        try {
            session.beginTransaction();
            session.merge(comprador);
            session.beginTransaction().commit();
        } catch (Exception e) {
            System.out.println("Error en actualizar: " + e.getMessage());
            session.beginTransaction().rollback();
        }
    }

    @Override
    public void eliminar(TCliente comprador) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        try {
            session.beginTransaction();
            session.delete(comprador);
            session.beginTransaction().commit();
        } catch (Exception e) {
            System.out.println("Error en eliminar: " + e.getMessage());
            session.beginTransaction().rollback();
        }
    }

    @Override
    public TCliente buscarPorId(String id) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        return (TCliente) session.load(TCliente.class, id);
    }

    @Override
    public List<TCliente> buscarTodos() {
        Session session = HibernateUtil.getSessionFactory().openSession();
        return session.createQuery("FROM TCliente").list();
    }
}
